// 全局变量
let currentPage = 1;
let pageSize = 6;
let allMenus = [];
let filteredMenus = [];
let currentFilter = 'all';

// DOM 元素
const menuGrid = document.getElementById('menuGrid');
const loading = document.getElementById('loading');
const error = document.getElementById('error');
const empty = document.getElementById('empty');
const searchInput = document.getElementById('searchInput');
const filterBtns = document.querySelectorAll('.filter-btn');
const prevPageBtn = document.getElementById('prevPage');
const nextPageBtn = document.getElementById('nextPage');
const pageInfo = document.getElementById('pageInfo');
const retryBtn = document.getElementById('retryBtn');
const menuModal = document.getElementById('menuModal');
const closeModal = document.getElementById('closeModal');

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
    setupEventListeners();
});

// 初始化应用
function initializeApp() {
    showLoading();
    loadMenus();
}

// 设置事件监听器
function setupEventListeners() {
    // 搜索功能
    searchInput.addEventListener('input', debounce(handleSearch, 300));
    
    // 筛选功能
    filterBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            filterBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            currentFilter = btn.dataset.filter;
            currentPage = 1;
            filterAndDisplayMenus();
        });
    });
    
    // 分页功能
    prevPageBtn.addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            displayMenus();
        }
    });
    
    nextPageBtn.addEventListener('click', () => {
        const maxPage = Math.ceil(filteredMenus.length / pageSize);
        if (currentPage < maxPage) {
            currentPage++;
            displayMenus();
        }
    });
    
    // 重试按钮
    retryBtn.addEventListener('click', () => {
        showLoading();
        loadMenus();
    });
    
    // 模态框关闭
    closeModal.addEventListener('click', closeMenuModal);
    menuModal.addEventListener('click', (e) => {
        if (e.target === menuModal) {
            closeMenuModal();
        }
    });
    
    // ESC键关闭模态框
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !menuModal.classList.contains('hidden')) {
            closeMenuModal();
        }
    });
}

// 加载菜单数据
async function loadMenus() {
    try {
        const response = await fetch(`http://localhost:9000/client/findAll/0/100`);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        
        allMenus = data;
        filteredMenus = [...allMenus];
        
        hideLoading();
        displayMenus();
        
    } catch (err) {
        console.error('加载菜单失败:', err);
        hideLoading();
        showError();
    }
}

// 显示加载状态
function showLoading() {
    loading.classList.remove('hidden');
    error.classList.add('hidden');
    empty.classList.add('hidden');
    menuGrid.classList.add('hidden');
}

// 隐藏加载状态
function hideLoading() {
    loading.classList.add('hidden');
    menuGrid.classList.remove('hidden');
}

// 显示错误状态
function showError() {
    error.classList.remove('hidden');
    loading.classList.add('hidden');
    empty.classList.add('hidden');
    menuGrid.classList.add('hidden');
}

// 显示空状态
function showEmpty() {
    empty.classList.remove('hidden');
    loading.classList.add('hidden');
    error.classList.add('hidden');
    menuGrid.classList.add('hidden');
}

// 处理搜索
function handleSearch() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    currentPage = 1;
    
    if (searchTerm === '') {
        filteredMenus = [...allMenus];
    } else {
        filteredMenus = allMenus.filter(menu => 
            menu.name.toLowerCase().includes(searchTerm) ||
            menu.flavor.toLowerCase().includes(searchTerm)
        );
    }
    
    filterAndDisplayMenus();
}

// 筛选和显示菜单
function filterAndDisplayMenus() {
    // 这里可以根据 currentFilter 进行额外的筛选
    // 目前简单实现，可以根据需要扩展
    displayMenus();
}

// 显示菜单
function displayMenus() {
    if (filteredMenus.length === 0) {
        showEmpty();
        return;
    }
    
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentMenus = filteredMenus.slice(startIndex, endIndex);
    
    renderMenuGrid(currentMenus);
    updatePagination();
}

// 渲染菜单网格
function renderMenuGrid(menus) {
    menuGrid.innerHTML = '';
    
    menus.forEach(menu => {
        const menuItem = createMenuItem(menu);
        menuGrid.appendChild(menuItem);
    });
}

// 创建菜单项
function createMenuItem(menu) {
    const menuItem = document.createElement('div');
    menuItem.className = 'menu-item';
    menuItem.innerHTML = `
        <div class="menu-item-image">
            <i class="fas fa-utensils"></i>
        </div>
        <div class="menu-item-content">
            <h3 class="menu-item-title">${escapeHtml(menu.name)}</h3>
            <p class="menu-item-flavor">${escapeHtml(menu.flavor)}</p>
            <div class="menu-item-price">¥${menu.price.toFixed(2)}</div>
        </div>
    `;
    
    // 添加点击事件
    menuItem.addEventListener('click', () => {
        openMenuModal(menu);
    });
    
    return menuItem;
}

// 更新分页信息
function updatePagination() {
    const maxPage = Math.ceil(filteredMenus.length / pageSize);
    
    prevPageBtn.disabled = currentPage <= 1;
    nextPageBtn.disabled = currentPage >= maxPage;
    
    pageInfo.textContent = `第 ${currentPage} 页，共 ${maxPage} 页`;
}

// 打开菜单详情模态框
function openMenuModal(menu) {
    document.getElementById('modalTitle').textContent = '菜品详情';
    document.getElementById('modalName').textContent = menu.name;
    document.getElementById('modalFlavor').textContent = menu.flavor;
    document.getElementById('modalPrice').textContent = `¥${menu.price.toFixed(2)}`;
    
    menuModal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';
}

// 关闭菜单详情模态框
function closeMenuModal() {
    menuModal.classList.add('hidden');
    document.body.style.overflow = 'auto';
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// HTML转义函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 工具函数：格式化价格
function formatPrice(price) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
    }).format(price);
}

// 工具函数：生成随机颜色
function getRandomColor() {
    const colors = [
        '#667eea', '#764ba2', '#f093fb', '#f5576c',
        '#4facfe', '#00f2fe', '#43e97b', '#38f9d7',
        '#fa709a', '#fee140', '#a8edea', '#fed6e3'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
}

// 工具函数：添加动画效果
function addAnimation(element, animationClass) {
    element.classList.add(animationClass);
    setTimeout(() => {
        element.classList.remove(animationClass);
    }, 1000);
}

// 错误处理
window.addEventListener('error', function(e) {
    console.error('JavaScript错误:', e.error);
});

// 网络状态监听
window.addEventListener('online', function() {
    console.log('网络已连接');
    if (allMenus.length === 0) {
        loadMenus();
    }
});

window.addEventListener('offline', function() {
    console.log('网络已断开');
}); 